<script setup>
/**
 * 如何要截图的是图片DOM、Canvas DOM、video DOM，都可以使用canvas的 drawImage(dom)绘制图片，然后ctx.toBlob(saveAs(blob))将图片截图
 * 但是像div, documnet.body 这种DOM需要使用 html2canvas 插件来截图
 */
import html2canvas from "html2canvas";
import { saveAs } from "file-saver";
import { onMounted, ref } from "vue";

const divRef = ref(null);
const imgRef = ref(null);
const canvasRef = ref(null);
const videoRef = ref(null);

const init = () => {
  const canvas = canvasRef.value;
  const ctx = canvas.getContext("2d");
  ctx.fillStyle = "#000";
  ctx.fillRect(0, 0, 80, 100);
};
onMounted(() => {
  init();
});

const saveScreen = () => {
  // body 截图
  //   htmlCanvasDom(document.body);
  // div 截图
  //   htmlCanvasDom(divRef.value, "div", "image/png");
  //   img 截图
  //   drawCanvasImage(imgRef.value);
  // canvas 截图
  //   createCanvas(canvasRef.value);
  //   video 截图
  drawCanvasImage(videoRef.value);
};

const createCanvas = (
  dom,
  imgName = "img",
  type = "image/jpeg",
  quality = 1
) => {
  canvasToBlob(dom, imgName, type, quality);
  s;
};

const drawCanvasImage = (
  dom,
  imgName = "img",
  type = "image/jpeg",
  quality = 1
) => {
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  canvas.width = dom.width;
  canvas.height = dom.height;

  ctx.drawImage(dom, 0, 0, dom.width, dom.height);
  canvasToBlob(canvas, imgName, type, quality);
};

// canvas.toBlob
const canvasToBlob = (canvas, imgName, type, quality) => {
  canvas.toBlob(
    (blob) => {
      saveAs(blob, imgName);
    },
    type,
    quality
  );
};

// html2canvas
const htmlCanvasDom = async (dom, imgName = "div", type = "image/jpeg") => {
  const canvas = await html2canvas(dom);
  canvasToBlob(canvas, imgName, type);
};
</script>

<template>
  <div>
    <div ref="divRef" class="div1">dsfjsadkl</div>
    <button @click="saveScreen">保存</button>
    <img ref="imgRef" src="/div.png" alt="" />
    <canvas ref="canvasRef" width="200" height="200"></canvas>
    <video ref="videoRef" width="320" height="240" controls>
      <source src="/orange.mp4" type="video/mp4" />
      您的浏览器不支持 video 标签。
    </video>
  </div>
</template>

<style scoped lang='less'>
.div1 {
  width: 200px;
  height: 200px;
  background: red;
}
</style>